package pers.mor.tomcat.filter;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

public class ApplicationFilterChain implements FilterChain {

    private Filter[] filters;
    private Servlet servlet;
    private int index = 0;

    public ApplicationFilterChain(List<Filter> filters, Servlet servlet) {
        this.filters = filters.toArray(new Filter[]{});
        this.servlet = servlet;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
        if (this.index < this.filters.length) {
            Filter filter = this.filters[this.index];
            this.index++;
            filter.doFilter(servletRequest, servletResponse, this);
        } else {
            this.index = 0;
            this.servlet.service(servletRequest, servletResponse);
        }
    }
}
